import React, { useEffect, useState, useMemo } from 'react';
import { List, Badge, Empty } from 'antd-mobile';
import { BellOutline } from 'antd-mobile-icons';
import request from '@/utils/request';
import styles from './index.less';
import { history } from 'umi';

interface Notification {
    id: number;
    title: string;
    content: string;
    type: string;
    is_read: boolean;
    created_at: string;
}

interface ChatRecord {
    chat_with_id: number;
    username: string;
    avatar_url: string;
    service_status: 'online' | 'offline' | 'busy';
    last_time: string;
    last_message: string;
    total_messages: number;
    unread_count: string;
    customerServiceId: number;
}

interface ApiResponse<T> {
    code: number;
    message: string;
    data: T;
}

const Message: React.FC = () => {
    const [notifications, setNotifications] = useState<Notification[]>([]);
    const [isCustomerService, setIsCustomerService] = useState(false);
    const [isTeacher, setIsTeacher] = useState(false);
    const [isAdmin, setIsAdmin] = useState(false);
    const [consultations, setConsultations] = useState<ChatRecord[]>([]);
    const [loading, setLoading] = useState(true);
    const [currentUser, setCurrentUser] = useState<any>(null);

    const fetchConsultations = async () => {
        try {
            const customerServiceId = isCustomerService ? currentUser?.id : null;

            const res = await request.get<any, ApiResponse<ChatRecord[]>>('/consultations', {
                params: {
                    customerServiceId,
                },
            });

            if (res.code === 200) {
                setConsultations(res.data);
            }
        } catch (error) {
            console.error('Failed to fetch consultations:', error);
        } finally {
            setLoading(false);
        }
    };

    // 获取通知列表
    useEffect(() => {
        const fetchNotifications = async () => {
            try {
                const res = await request.get<any, ApiResponse<Notification[]>>('/notifications');
                if (res.code === 200) {
                    setNotifications(res.data);
                }
            } catch (error) {
                console.error('Failed to fetch notifications:', error);
            }
        };

        fetchNotifications();
    }, []);

    // 标记消息已读
    const handleMessageRead = async (id: number) => {
        try {
            const res = await request.post<any, ApiResponse<any>>(`/notifications/${id}/read`);
            if (res.code === 200) {
                setNotifications(prev => 
                    prev.map(notification => 
                        notification.id === id 
                            ? { ...notification, is_read: true }
                            : notification
                    )
                );
            }
        } catch (error) {
            console.error('Failed to mark notification as read:', error);
        }
    };

    // 检查用户角色
    useEffect(() => {
        const checkRole = async () => {
            try {
                const res = await request.get<any, ApiResponse<{ role_name: string }>>('/user/info');
                if (res.code === 200) {
                    setCurrentUser(res.data);
                    if (res.data.role_name === 'customer_service') {
                        setIsCustomerService(true);
                        fetchConsultations();
                    } else if (res.data.role_name === 'teacher') {
                        setIsTeacher(true);
                    } else if (res.data.role_name === 'admin') {
                        setIsAdmin(true);
                    } else {
                        fetchConsultations();
                    }
                }
            } catch (error) {
                console.error('Failed to check role:', error);
            }
        };
        checkRole();
    }, []);

    // 对聊天记录进行去重和排序
    const uniqueChats = useMemo(() => {
        const uniqueMap = new Map();
        consultations.forEach(chat => {
            const existing = uniqueMap.get(chat.chat_with_id);
            if (!existing || new Date(chat.last_time) > new Date(existing.last_time)) {
                uniqueMap.set(chat.chat_with_id, chat);
            }
        });
        return Array.from(uniqueMap.values())
            .sort((a, b) => new Date(b.last_time).getTime() - new Date(a.last_time).getTime());
    }, [consultations]);

    return (
        <div className={styles.messageContainer}>
            <div className={styles.navbar}>
                <span>消息中心</span>
                <BellOutline className={styles.bellIcon} />
            </div>

            {isCustomerService || (!isTeacher && !isAdmin) ? (
                <div className={styles.consultationSection}>
                    <div className={styles.sectionTitle}>咨询消息</div>
                    {uniqueChats.length > 0 ? (
                        <List className={styles.messageList}>
                            {uniqueChats.map((chat) => (
                                <List.Item
                                    key={chat.chat_with_id}
                                    prefix={
                                        <div className={styles.avatarWrapper}>
                                            <img 
                                                src={chat.avatar_url} 
                                                className={styles.avatar}
                                                alt={chat.username}
                                            />
                                            <span className={`${styles.status} ${styles[chat.service_status]}`} />
                                        </div>
                                    }
                                    onClick={() => history.push(`/chat/${chat.chat_partner_id}`)}
                                    arrow={false}
                                >
                                    <div className={styles.chatInfo}>
                                        <div className={styles.topLine}>
                                            <span className={styles.name}>{chat.username}</span>
                                            <span className={styles.time}>
                                                {new Date(chat.created_at).toLocaleString()}
                                            </span>
                                        </div>
                                        <div className={styles.bottomLine}>
                                            <span className={styles.lastMessage}>{chat.content}</span>
                                            {Number(chat.unread_count) > 0 && (
                                                <Badge content={chat.unread_count} />
                                            )}
                                        </div>
                                    </div>
                                </List.Item>
                            ))}
                        </List>
                    ) : (
                        <Empty
                            className={styles.emptyContainer}
                            image="https://gw.alipayobjects.com/zos/antfincdn/ZHrcdLPrvN/empty.svg"
                            description={
                                <div className={styles.emptyText}>
                                    <p>暂无咨询消息</p>
                                    <p className={styles.emptySubText}>有新的咨询时会在这里显示</p>
                                </div>
                            }
                        />
                    )}
                </div>
            ) : null}

            <div className={styles.sectionTitle}>系统通知</div>
            {notifications.length > 0 ? (
                <List className={styles.messageList}>
                    {notifications.map(notification => (
                        <List.Item
                            key={notification.id}
                            onClick={() => handleMessageRead(notification.id)}
                            className={styles.messageItem}
                        >
                            <Badge
                                content=""
                                className={styles.badge}
                                style={{ 
                                    display: notification.is_read ? 'block' : 'block',
                                    position: 'absolute',
                                    top: '50%',
                                    left: '12px',
                                    transform: 'translateY(-50%)'
                                }}
                            />
                            <div className={styles.messageContent}>
                                <div className={styles.messageHeader}>
                                    <span className={styles.messageType}>
                                        {notification.type}
                                    </span>
                                    <span className={styles.messageTime}>
                                        {new Date(notification.created_at).toLocaleDateString()}
                                    </span>
                                </div>
                                <div className={styles.messageTitle}>
                                    {notification.title}
                                </div>
                                <div className={styles.messageText}>
                                    {notification.content}
                                </div>
                            </div>
                        </List.Item>
                    ))}
                </List>
            ) : (
                <div className={styles.emptyContainer}>
                    <Empty description='暂无消息' />
                </div>
            )}
        </div>
    );
};

export default Message; 